package com.ncloud.crm.dubboservice.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.dubboservice.AdminDashboardService;
import com.ncloud.crm.mapper.AdminDashboardMapper;



@Service
public class AdminDashboardServiceImpl implements AdminDashboardService {
	private static final Logger logger = LogManager.getLogger(AdminDashboardService.class);
	@Autowired
	public AdminDashboardMapper dashboardMapper;
	

	//查询本自然年内每月云网平台收入（渠道结算金额）
	@Override
	public JSONArray getSumBalanceByMonth(JSONObject json) {
		JSONArray jsonArray=new JSONArray();
		List<Map<Object,Object>> sumList=new ArrayList<Map<Object,Object>>();
		List<Object> monthCount=new ArrayList<Object>();
		try {				
			String year = ThisMonth().get("year");
			String taskId = "1001";
			for(int m=0;m<12;m++){
				monthCount.add(0);
			}
			//每月的
			sumList=dashboardMapper.getSumByYearMonth(taskId, year);			
			for (int i = 0; i < sumList.size(); i++) {
				Map<Object,Object> map=new HashMap<Object, Object>();
				map=sumList.get(i);
				String month = map.get("month").toString();
				boolean flag=map.containsKey("task_value");
				String taskValue = "0";
				if(flag){
					taskValue=map.get("task_value").toString();
					}
				
				String f1 = moneyChanges(taskValue);
				
				int setId=Integer.valueOf(month);
				monthCount.set(setId-1,f1);
			}
			jsonArray.add(monthCount);
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonArray;
	}
		
	//返回每月战区销售量统计（渠道结算金额）	
	@Override
	public JSONObject getSumBalanceByChnlAndMonth(JSONObject jsons) {
		List<Map<Object,Object>> listInfo = new ArrayList<Map<Object,Object>>();
		JSONObject json = new JSONObject();
		try {				
			List<Object> chnllist=new ArrayList<Object>();
			List<Object> datalist=new ArrayList<Object>();
			listInfo = dashboardMapper.getChnlBill();
			for(int i=0 ;i<listInfo.size();i++){
				Map<Object,Object> map = new HashMap<Object, Object>();
				map = listInfo.get(i);
				String key = map.get("chnl_name").toString();
				boolean flag=map.containsKey("fee");
				String fee = "0";
				if(flag){
					fee=map.get("fee").toString();
					}
				String f1 = moneyChangesMillion(fee);
				chnllist.add(key);
				datalist.add(f1);			
			}
			json.put("chnl",chnllist);
			json.put("value",datalist);
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}
	
	//战区销售数据排名top5
	@Override
	public JSONArray getChnlByTop5(JSONObject json){
		List<Map<Object,Object>> listInfo = new ArrayList<Map<Object,Object>>();
		String thisMonth = ThisMonth().get("month");
		String year = LastMonth().get("year");
		String lastMonth = LastMonth().get("month");	
		JSONArray jsonArray = new JSONArray();
		try {				
			String taskId = "1002";
			//listInfo = dashboardMapper.getChnlByTop5();
			listInfo = dashboardMapper.getSumByMonth2(taskId,year,thisMonth);
			for(int i = 0 ; i<listInfo.size();i++ ){
				Map<Object,Object> map = new HashMap<Object, Object>();
				Map<Object,Object> mapInfo = new HashMap<Object, Object>();
				map = listInfo.get(i);	
				//战区name
				String taskKey = map.get("task_key").toString();
				//战区本月销售量
				
				String Sum = null;
				boolean flag=map.containsKey("task_value");
				String taskValue = "0";
				if(flag){
					taskValue=map.get("task_value").toString();
					}
				String f = moneyChanges(taskValue);
				
				//战区ID
				String taskValue2 = null;
				if(flag){
					taskValue2=map.get("task_value2").toString();
					}
				
				//查询该战区上一个月的销售量
				 Sum = dashboardMapper.getSumByChnlAndMonth(taskId, year, lastMonth, taskValue2);
				 double f1= 0.00;
				 if(Sum == null || Sum==""){
					f1=0.00;
				}else{
					//销量转int
					Long thisSum = Long.parseLong(taskValue.toString());
					Long lastSum = Long.parseLong(Sum);
					
					Long minus = thisSum - lastSum; 
					double mm = (double)minus/lastSum;
					BigDecimal ss = new BigDecimal(mm);  
					f1 = ss.setScale(2,RoundingMode.HALF_UP).doubleValue();
				}
							
				 int monthN=Integer.parseInt(thisMonth);
				mapInfo.put("num",i+1);
				//渠道名称
				mapInfo.put("chnlName", taskKey);
				//月份
				mapInfo.put("month",monthN);
				//销量
				mapInfo.put("sales", f);
				//同比增或减
				mapInfo.put("from", f1);
				jsonArray.add(mapInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonArray;		
	}
	
	//统计客户节点所处的地域
	@Override
	public JSONArray getCustomerNodeByCity(JSONObject json){
		List<Map<Object,Object>> listInfo = new ArrayList<Map<Object,Object>>();
		JSONArray jsonArray = new JSONArray();
		try {							
			listInfo = dashboardMapper.getCustomerNodeByCity();
			for(int i = 0 ; i<listInfo.size();i++ ){
				Map<Object,Object> map = new HashMap<Object, Object>();
				Map<Object,Object> mapInfo = new HashMap<Object, Object>();
				map = listInfo.get(i);
		
				String taskKey = map.get("city").toString();
				boolean flag=map.containsKey("count");
				String taskValue = "0";
				if(flag){
					taskValue=map.get("count").toString();
					}
				//{ name: "海门", value: 9 },
				mapInfo.put("name", taskKey);
				mapInfo.put("value", taskValue);
				jsonArray.add(mapInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonArray;		
	}
	
	//行业分布统计
	@Override
	public JSONArray getCountByIndustry(JSONObject json){
		List<Map<Object,Object>> listInfo = new ArrayList<Map<Object,Object>>();
		JSONArray jsonArray = new JSONArray();
		try {							
			listInfo = dashboardMapper.getCountByIndustry();
			for(int i = 0 ; i<listInfo.size();i++ ){
				Map<Object,Object> map = new HashMap<Object, Object>();
				Map<Object,Object> mapInfo = new HashMap<Object, Object>();
				map = listInfo.get(i);
				String taskKey = map.get("industry").toString();
				boolean flag=map.containsKey("count");
				String taskValue = "0";
				if(flag){
					taskValue=map.get("count").toString();
					}
				//{ name: "海门", value: 9 },
				mapInfo.put("name", taskKey);
				mapInfo.put("value", taskValue);
				jsonArray.add(mapInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return jsonArray;		
	}
	
	//本年内各个产品、业务的销售金额
		@Override
		public JSONArray getCountByProduct(JSONObject json){
			List<Map<Object,Object>> listInfoProduct = new ArrayList<Map<Object,Object>>();
			List<Map<Object,Object>> listInfoDiscnt = new ArrayList<Map<Object,Object>>();
			List<Map<Object,Object>> listName = new ArrayList<Map<Object,Object>>();
			listName = dashboardMapper.getProductNameList();
			JSONArray jsonArray = new JSONArray();
			JSONObject jsonObject = new JSONObject();
			String year = ThisMonth().get("year");			
			try {
				//本年内各个产品的销售金额
				String taskId1 = "1005";
				listInfoProduct = dashboardMapper.getYearCountProduct(taskId1,year);
				List<Map<Object,Object>> listvalues = new ArrayList<Map<Object,Object>>();
				for(int i=0;i<listInfoProduct.size();i++){
					Map<Object,Object> map=new HashMap<Object, Object>();
					map=listInfoProduct.get(i);
					
					boolean flag=map.containsKey("value");
					String value = "0";
					if(flag){
						value=map.get("value").toString();
						}
					
					String values=moneyChanges(value);
					map.put("value", values);
					listvalues.add(map);
				}
				jsonObject.put("name","productType");
				jsonObject.put("value",listvalues);
				jsonArray.add(jsonObject);
				//本年内各个套餐的销售金额
				String taskId2 = "1004";
				for(int i=0;i<listName.size();i++){
					JSONObject jsons = new JSONObject();
					Map<Object,Object> listMap=new HashMap<Object, Object>();
					listMap=listName.get(i);
					String name=listMap.get("prod_name").toString();
					listInfoDiscnt=dashboardMapper.getYearCountDiscnt(taskId2, year, name);
					
					List<Map<Object,Object>> listMaps=new ArrayList<Map<Object,Object>>();
					if(listInfoDiscnt != null&&listInfoDiscnt.size()>0){
						for(int k=0;k<listInfoDiscnt.size();k++){
						Map<Object,Object> map=new HashMap<Object, Object>();
						map=listInfoDiscnt.get(k);
						
						boolean flag=map.containsKey("value");
						String taskValue = "0";
						if(flag){
							taskValue=map.get("value").toString();
							}
												
						String values=moneyChanges(taskValue);
						map.put("value", values);
						listMaps.add(map);
						}
						jsons.put("name",name);
						jsons.put("value",listMaps);
						jsonArray.add(jsons);
					}
					
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}
			return jsonArray;		
		}
		
		
		//统计产品结算单的总额（渠道结算费用）
		@Override
		public JSONArray getSettlementByProduct(JSONObject json){
			String tastId = "1003";
			String year = ThisMonth().get("year");
			JSONArray jsonArray = new JSONArray();			
		try{	
			//得到产品列表			prod_type
			List<Map<Object,Object>> listName = new ArrayList<Map<Object,Object>>();
			listName = dashboardMapper.getProductNameList();						
			for(int i=0;i<listName.size();i++){
				JSONObject jsons= new JSONObject();
				List<Object> monthCount=new ArrayList<Object>();
				for(int m=0;m<12;m++){
					monthCount.add(0);
				}
				Map<Object,Object> listMap=new HashMap<Object, Object>();
				List<Object> dataList=new ArrayList<Object>();
				listMap=listName.get(i);
				String taskKey=listMap.get("prod_name").toString();
				String prodType=listMap.get("prod_type").toString();
				List<Map<Object,Object>> listProduct = new ArrayList<Map<Object,Object>>();
				listProduct=dashboardMapper.getProductByMonth(tastId, year,taskKey);
					for(int k=0;k<listProduct.size();k++){
						dataList.add(listProduct.get(k));
						Map<Object,Object> map=new HashMap<Object, Object>();
						map=listProduct.get(k);
						boolean flag=map.containsKey("month");
						int month = 0;
						if(flag){
							month=Integer.valueOf(map.get("month").toString());
							}
						boolean flag2=map.containsKey("task_value");
						Long count = 0L;
						String count_d="0.00";
						if(flag2){
							count=Long.parseLong(map.get("task_value").toString());
							count_d=moneyChanges(String.valueOf(count));
							}	
						if(count >0){
							monthCount.set(month-1,count_d);
						}
					}
					jsons.put("name",taskKey);
					jsons.put("value", monthCount);
					jsons.put("type",prodType);
					jsonArray.add(jsons);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
			return jsonArray;
			
		}
		
		public Map<String,String> TwoMonth(){
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MONTH, -2);
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
			String time = format.format(cal.getTime());
			String year = time.split("-")[0];
			String month = time.split("-")[1];
			Map<String,String> dateMap = new HashMap<String, String>();
			dateMap.put("year", year);
			dateMap.put("month",month);
			return dateMap;		
		}	
		
	
	public Map<String,String> LastMonth(){
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -1);
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
		String time = format.format(cal.getTime());
		String year = time.split("-")[0];
		String month = time.split("-")[1];
		Map<String,String> dateMap = new HashMap<String, String>();
		dateMap.put("year", year);
		dateMap.put("month",month);
		return dateMap;		
	}
	public Map<String, String> ThisMonth(){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String time = sdf.format(date);
		String year = time.split("-")[0];
		String month = time.split("-")[1];
		String day = time.split("-")[2];
		Map<String,String> dateMap = new HashMap<String, String>();
		dateMap.put("year", year);
		dateMap.put("month",month);
		dateMap.put("day",day);
		return dateMap;		
	}
	//分变元保留两位小数
	public String moneyChanges(String str){
		
		double values = (double)Long.parseLong(str)/100;
		BigDecimal ss = new BigDecimal(values); 
		double f1 = ss.setScale(2,RoundingMode.HALF_UP).doubleValue();
		DecimalFormat df = new DecimalFormat("######0.00"); 
		String res=df.format(f1);
		return res;
	}
	//分变万保留两位小数
		public String moneyChangesMillion(String str){
			
			double values = (double)Long.parseLong(str)/1000000;
			BigDecimal ss = new BigDecimal(values); 
			double f1 = ss.setScale(2,RoundingMode.HALF_UP).doubleValue();
			DecimalFormat df = new DecimalFormat("######0.00"); 
			String res=df.format(f1);
			return res;
		}
}